<?php
/**
 * 微信接口门面类
 */
namespace Org\Weixin;

use Org\Weixin\Wechat;//微信基础类。
use Org\Weixin\JSSDK;//JSSDK基础类
use Org\Weixin\WechatAuth;//微信网页授权类
use Org\Weixin\wxpay\WxPayApi;
use Org\Weixin\wxpay\JsApiPay;//微信网页支付实现类
use Org\Weixin\wxpay\WxPayUnifiedOrder;
use Org\Weixin\wxpay\WxPayOrderQuery;
use Org\Weixin\wxpay\WxPayRefund;//微信退款类
use Org\Weixin\ComPay;//企业营销类
use Org\Weixin\wxpay\RedBag;//红包类
use Org\Weixin\wxpay\WxPayBizPayUrl;//扫码支付类

class WxFacade
{
    private $weixin;

    private static $appid = '';

    private static $appsecret = '';

    private static $mchid = '';

    private static $mchkey = '';

    private static $token = '';

    private static $notify_url = '';

	/**
     * [设置门面类参数]
     * @param array $data [description]
     */
	public function setConfig( $data = array() )
	{	
		if( is_array($data) )
		{
			self::$appid         = !empty($data['appid'])?$data['appid']:'';
			self::$appsecret     = !empty($data['appsecret'])?$data['appsecret']:'';
			self::$mchid         = !empty($data['mchid'])?$data['mchid']:'';
			self::$mchkey        = !empty($data['mchkey'])?$data['mchkey']:'';
            self::$token        = !empty($data['token'])?$data['token']:'';
			self::$notify_url    = !empty($data['notify_url'])?$data['notify_url']:'';
		}
		WxPayApi::setConfig($data);
	}
	
    /**
     * [微信基础类，负责开发者模式开启验证及事件或消息回调]
     * @return [type] [description]
     */
    public static function createWechat()
    {
        //第一参数为token，必填；第二参数为appid，第三参数为加密KEY，在密文模式时皆为必填
        $wechat = Wechat(self::$token);
        return $wechat;
    }

    /**
     * [获取jssdk配置数据]
     * @return [type] [description]
     */
    public static function createJSSDK()
    {
        $accessToken = self::getToken();
        $jssdk = new JSSDK(self::$appid, $accessToken );
        return $jssdk->getSignPackage();
    }

    /**
     * [微信内部浏览器发起支付]
     * @param  [type] $openid [用户在此公众号内的uid，唯一验证参数]
     * @param  [type] $data   [订单信息，包括金额，订单编号，发起人等信息]
     * @return [type]         [description]
     */
    public static function applyPay( $openid , $data )
    {
        $tools = new JsApiPay(self::$appid,self::$appsecret);
        $Out_trade_no = $data['order_no'];
        $Body         = $Out_trade_no;
        $Total_fee    = $data['order_total'];
        
        //设置支付
        $input = new WxPayUnifiedOrder();
        $input->SetBody($Body);
        $input->SetOut_trade_no($Out_trade_no);
        $input->SetTotal_fee($Total_fee);
        $input->SetNotify_url( self::$notify_url );
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = WxPayApi::unifiedOrder($input);
        if($order['result_code']=='FAIL')
        {
			return tp_return( 1 , $order['err_code_des'] );
        }
        elseif($order['return_code']=='FAIL'){
            return tp_return( 1 , $order['return_msg'] );
        }
        else{
            $jsApiParameters = $tools->GetJsApiParameters($order);
			return tp_return( 0 , 'success' , $jsApiParameters );
        }
		
    }

    /**
     * [微信支付查询]
     * @return [type] [description]
     */
    public static function queryOrder( $out_trade_no )
    {
        $input = new WxPayOrderQuery();
        $input->SetOut_trade_no($out_trade_no);
        $data = WxPayApi::orderQuery($input);
        if($data['trade_state'] == 'SUCCESS' ){
            return tp_return(0,'订单已支付');
        }elseif($data['trade_state'] == 'REFUND' ){
             return tp_return(1,'订单已退款');
        }else{
            return tp_return(2001,'订单未付款');
        }
    }

    /**
     * [refund description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function refund( $data )
    {
        $refund_fee = $order_total;
        $input = new WxPayRefund();
        $input->SetOut_trade_no($data['order_no']);
        $input->SetTotal_fee($data['order_total']);
        $input->SetRefund_fee($data['order_total']);
        $input->SetOut_refund_no(self::$mchid.date("YmdHis"));
        $input->SetOp_user_id(self::$mchid);
        $ret = WxPayApi::refund($input);
        if($ret['return_code']=='SUCCESS')
        {
            if($ret['return_code']=='SUCCESS')
            {
                return tp_return( 0 , 'ok' , $ret );
            }
            else{
                return tp_return( 2 , $ret['result_code'] );
            }
        }
        else{
            return tp_return( 1 , $ret['return_msg'] );
        }
    }

    /**
     * [红包]
     * @return [type] [description]
     */
    public static function redBag( $openid , $data )
    {
        $rb = new ComPay();
        $rb->setOpenid($openid);
        $rb->setAmount($data['total']*100);
        $rb->setMchid(self::$mchid);
        $rb->setApiKey(self::$mchkey);
        $rb->setMchAppid(self::$appid);
        $rb->setSendName($data['name']);
        $rb->setTotalNum($data['num']);
        $rb->setWishing($data['wishing']);
        $rb->setActName($data['act_name']);
        $rb->setDesc($data['desc']);
        
        $ret = $rb->RedBag();
        if($ret)
        {
            return tp_return( 0 , 'ok' );
        }
        else{
            return tp_return( 1 , $rb->error() );
        }
    }

    /**
     * [企业支付]
     * @param  [vachar] $openid [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function comPay( $openid , $data )
    {
        $rb = new ComPay();
        $fee = $data['total']*100;
        $body = $data['body'];
        $rb->setAmount($fee);
        $rb->setDesc($body);     
        $rb->setOpenid($openid);
        $rb->setMchid(self::$mchid);
        $rb->setApiKey(self::$mchkey);
        $rb->setMchAppid(self::$appid);
        $res =  $rb->ComPay();
        if($res)
        {
            return tp_return( 0 , '发送成功');
        }
        else{
            return tp_return( 1 , $rb->error());
        }
    }

    /**
     * [getPrePayUrl description]
     * @param  [type] $pro_id [description]
     * @return [type]         [description]
     */
    public static function getPrePayUrl( $pro_id )
    {
        $biz = new WxPayBizPayUrl();
        $biz->SetProduct_id( $pro_id );
        $biz->SetAppid( self::$appid );
        $biz->SetMch_id( self::$mchid );
        $biz->SetTime_stamp(time());
        $biz->SetNonce_str();
        $values = WxpayApi::bizpayurl($biz);
        $url = "weixin://wxpay/bizpayurl?" . ToUrlParams($values);
        return $url;
    }

    /**
     * [getPayUrl description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function getPayUrl( $data )
    {
        $input = new WxPayUnifiedOrder();
        $input->SetBody($data['body']);//商品或支付单简要描述
        $input->SetAttach($data['attch']);//设置附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        $input->SetGoods_tag($data['goodtag']);//商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
        $input->SetProduct_id($data['pro_id']);
        $input->SetTotal_fee($data['total']);
        $input->SetOut_trade_no(self::$mchid.date("YmdHis"));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url(self::$notify_url);
        $input->SetTrade_type("NATIVE");
        $result = WxPayApi::unifiedOrder($input);
        if($result["return_code"] == 'SUCCESS' )
        {
            if($result["result_code"] == 'SUCCESS' )
            {
                return tp_return( 0 , 'ok' ,$result["code_url"]);
            }
            else{
                return tp_return(2,$result['err_code_des']);
            }
            
        }
        else{
            return tp_return(1,$result['return_msg']);
        }
    }

    public static function getAddr()
    {
        $tools = new JsApiPay(self::$appid,self::$appsecret);
        $tools->GetOpenid();
        $editAddress = $tools->GetEditAddressParameters();
        return $editAddress;
    }

    /**
     * 资源文件上传方法
     * @param  string $type 上传的资源类型
     * @return string       媒体资源ID
     */
    public static function upload( $type , $src )
    {
        $token = session("token");

        if($token){
            $auth = new WechatAuth(self::$appid, self::$appsecret, $token);
        } else {
            $auth  = new WechatAuth(self::$appid, self::$appsecret);
            $token = $auth->getAccessToken();

            session(array('expire' => $token['expires_in']));
            session("token", $token['access_token']);
        }

        switch ($type) {
            case 'image':
                $filename = $src;
                $media    = $auth->materialAddMaterial($filename, $type);
                break;

            case 'voice':
                $filename = $src;
                $media    = $auth->materialAddMaterial($filename, $type);
                break;

            case 'video':
                $filename    = $src;
                $discription = array('title' => '视频标题', 'introduction' => '视频描述');
                $media       = $auth->materialAddMaterial($filename, $type, $discription);
                break;

            case 'thumb':
                $filename = $src;
                $media    = $auth->materialAddMaterial($filename, $type);
                break;
            
            default:
                return '';
        }

        if($media["errcode"] == 42001)//access_token expired
        { 
            session("token", null);
            self::upload($type,$src);
        }
        else{
            return $media['media_id'];
        }
        
    }

    /**
     * [获取网页授权token，和self::$token（微信token）不同]
     * @return [type] [description]
     */
    public static function getToken()
    {
        $token = S('token');
        if(!$token){
            $WechatAuth = new WechatAuth( self::$appid , self::$appsecret );
            $AccessToken = $WechatAuth->getAccessToken();
            $token = $AccessToken['access_token'];
            S('token',$token,7000);
        }
        return $token;
    }

    /**
     * [获取用户在微信公众号的uid]
     * @return [type] [description]
     */
    public static function getOpenid()
    {
        $openid = session('openid');
        if(!$openid){
            $tools = new JsApiPay(self::$appid,self::$appsecret);
            $openid = $tools->GetOpenid();
            session('openid',$openid); 
        }
        return $openid;
    }
	
    /**
     * [获取公众号appid]
     * @return [type] [description]
     */
	public static function getAppid()
    {
        return self::$appid;
    }
}
